package cn.itcast.filter;

import cn.itcast.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
//@WebFilter("/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取请求路径

        StringBuffer requestURL = request.getRequestURL();
        //2。判断是否登录请求
        if (requestURL.toString().contains("login")){
            //2.1放行
            filterChain.doFilter(request,response);
            //不用执行后面的逻辑
            return;
        }
        //3.获取请求头
        String token = request.getHeader("token");
        //4.判断是有token
        if (token==null || token.isEmpty()){
            //设置响应状态码
            response.setStatus(401);
            return;
        }
        try {
            //5.解析token
            Claims claims = JwtUtils.parseJWT(token);
            //可以获取信息
            Object name = claims.get("name");
            log.info("--------------------token - name = "+name);
            //放行
            filterChain.doFilter(request,response);
        } catch (Exception e) {
            //设置响应状态码，之间返回
            response.setStatus(401);
        }


    }
}
